"""
Author: ZhengShiQi
DateTime: 2025/9/15
FileName: load_mocks_to_wiremock.py
Description: 从数据库加载Mock配置到WireMock
"""

import sys
import os
import json
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy.orm import Session
from app.models.database import engine, SessionLocal
from app.services.db_service import get_all_mock_apis
from app.services.mock_service import WireMockService
from app.models.schemas import MockApiCreate


def load_mocks_to_wiremock():
    """从数据库加载所有Mock配置到WireMock"""
    # 创建数据库会话
    session = SessionLocal()
    
    try:
        # 获取所有Mock配置
        mock_apis = get_all_mock_apis(session)
        
        # 初始化WireMock服务
        wiremock_service = WireMockService()
        
        # 遍历所有Mock配置并加载到WireMock
        for mock_api in mock_apis:
            # 处理body字段，确保它是字典类型
            body = mock_api.body
            if isinstance(body, str):
                try:
                    body = json.loads(body)
                except json.JSONDecodeError:
                    body = {}
            
            # 构造MockApiCreate对象
            mock_api_create = MockApiCreate(
                name=mock_api.name,
                url=mock_api.url,
                method=mock_api.method,
                headers=mock_api.headers or {},
                body=body,
                status_code=mock_api.status_code,
                status=mock_api.status
            )
            
            # 如果已经有wiremock_id，则更新映射；否则创建新的映射
            if mock_api.wiremock_id:
                try:
                    # 尝试更新现有映射
                    wiremock_service.update_mapping(mock_api.wiremock_id, mock_api.method, mock_api_create)
                    print(f"更新成功")
                except Exception as e:
                    print(f"更新映射失败 {mock_api.wiremock_id}: {str(e)}")
                    # 如果更新失败，可能是因为映射不存在，创建新的映射
                    response = wiremock_service.create_mapping(mock_api_create)
                    # 更新数据库中的wiremock_id
                    mock_api.wiremock_id = response.get('id')
                    session.commit()
            else:
                # 创建新的映射
                response = wiremock_service.create_mapping(mock_api_create)
                # 更新数据库中的wiremock_id
                mock_api.wiremock_id = response.get('id')
                session.commit()

        print(f"成功加载 {len(mock_apis)} 个Mock配置到WireMock")

    except Exception as e:
        print(f"加载Mock配置到WireMock时出错: {str(e)}")
        raise

    finally:
        session.close()


def main():
    """主函数"""
    load_mocks_to_wiremock()


if __name__ == "__main__":
    main()